# !/usr/bin/env python
# -*-coding:utf-8 -*-

"""
# File       : alarm_count_view.py
# Time       ：2023/10/31 14:00
# Author     ：YangYong
# version    ：python 3.10
# Description：首页运行状态视图
"""
from flask_restx import fields
from sqlalchemy import func

from apis.notice.model.alarm import Alarm
from apis.data_screen.schema.process_alarm_count_schema import ProcessAlarmCountSchema
from apis.home import home_ns

from public.api_utils.api_decorator import handle_api_error
from public.base_model import db
from public.base_response import generate_response, MarshalModel
from public.base_view import AbstractView

alarm_count = home_ns.model('alarm_count', {'name': fields.String(), 'value': fields.String()})
alarm_count_marshal = MarshalModel('alarm_count', home_ns)


class AlarmCountView(AbstractView):
    url = '/alarm_count'

    def __init__(self, *args, **kwargs):
        super(AlarmCountView, self).__init__(*args, **kwargs)

    @handle_api_error()
    @home_ns.doc(description='首页运行状态')
    @home_ns.marshal_with(alarm_count_marshal.list_response(alarm_count, is_db=False))
    def get(self):
        """首页运行状态"""
        response_data = list()
        objs = db.session.query(
            Alarm.process_name.label('name'),
            func.count(1).label('value')
        ).filter(Alarm.active == 1).group_by('name').all()
        info = ProcessAlarmCountSchema().dump(objs, many=True)

        for item in info:
            response_data.append({'name': item.get('name'), 'value': item.get('value')})

        response_data.sort(key=lambda val: val.get('value'), reverse=True)
        return generate_response(response_data)
